package com.example.wearing.find;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.wearing.R;
import com.example.wearing.javabean.Post;
import com.example.wearing.javabean.Reply;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.tools.PostAdapter;
import com.example.wearing.tools.ReplyAdapter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

public class PostDetailActivity extends AppCompatActivity {

    /*
    页面逻辑：
    1、初始化控件
    2、数据库——帖子评论——listview和adapter显示
    3、点击btn进行评论，评论后刷新显示
     */

    private int postId, userId;
    private String postTitle, postDetail, postTime, postUser;
    private Bitmap postImgBitmap, postUserImgBitmap;
    private int postLikeNum, postReplyNum;
    private String replyText, replyTime;
    private String username;
    private ArrayList<Reply> replyList = new ArrayList<>();
    private String jdbcUser, jdbcUrl, jdbcPassword;

    private TextView titleView, detailView, timeView, userView, likeNumView, replyNumView;
    private ImageView imageView, userImgView, likeImgView;
    private ListView replyListView;
    private boolean likeStatus = false;

    private final static String TAG = "PostDetailActivity";
    private Handler handler = new Handler();
    ReplyAdapter replyAdapter;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_detail);

        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        init();//初始化

        //开启线程，查询所有评论
        Thread thread = new Thread(getReplyRun);
        thread.start();

        //开启线程，查询点赞信息
        Thread thread2 = new Thread(getLikeRun);
        thread2.start();

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){

                if(msg.what == 1){
                    Log.i(TAG, "handleMessage: 收到发布新评论消息");
                    //接收消息（提交评论）
                    int res = (int) msg.obj;
                    if(res == 1){
                        //发布成功
                        Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                        //更改该界面的replyNum
                        postReplyNum = postReplyNum+1;
                        replyNumView.setText(String.valueOf(postReplyNum));
                        //更新adapter
                        replyAdapter.notifyDataSetChanged();

                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                    }
                }else if(msg.what == 2){
                    Log.i(TAG, "handleMessage: 收到查询回复列表的消息");

                    //设置adapter，显示列表
                    replyAdapter = new ReplyAdapter(PostDetailActivity.this,
                            R.layout.reply_list,
                            replyList);
                    replyListView.setAdapter(replyAdapter);
                }else if(msg.what == 3){
                    //用于初始化点赞信息
                    Log.i(TAG, "handleMessage: 收到查询点赞数据的消息");
                    if(likeStatus){
                        //点过赞——图标点亮
                        likeImgView.setImageResource(R.drawable.zan2);
                    }

                }else if(msg.what == 4){
                    Log.i(TAG, "handleMessage: 收到点击“点赞”的消息");
                    int res = (int) msg.obj;
                    if(res == 1){
                        //点赞
                        //更改该界面的likeNum
                        postLikeNum = postLikeNum+1;
                        likeNumView.setText(String.valueOf(postLikeNum));
                        //更改界面的like图标
                        likeImgView.setImageResource(R.drawable.zan2);
                        Toast.makeText(getApplicationContext(), "点赞成功", Toast.LENGTH_SHORT).show();
                    }else if(res == 0){
                        //取消点赞
                        //更改该界面的likeNum
                        postLikeNum = postLikeNum-1;
                        likeNumView.setText(String.valueOf(postLikeNum));
                        //更改界面的like图标
                        likeImgView.setImageResource(R.drawable.zan);
                        Toast.makeText(getApplicationContext(), "取消成功", Toast.LENGTH_SHORT).show();
                    }

                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    //初始化函数(控件初始化、intent接收数据、控件放置数据、sharedpreferences中找用户名)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void init(){

        //控件初始化
        titleView = findViewById(R.id.title);
        detailView = findViewById(R.id.detail);
        timeView = findViewById(R.id.time);
        userView = findViewById(R.id.user);
        likeNumView = findViewById(R.id.likeNum);
        replyNumView = findViewById(R.id.replyNum);
        imageView = findViewById(R.id.image);
        userImgView = findViewById(R.id.userImg);
        replyListView = findViewById(R.id.replyList);
        likeImgView = findViewById(R.id.likeImg);

        //从intent中接收数据
        Intent intent = getIntent();
        postId = intent.getIntExtra("postID",0);
        postTitle = intent.getStringExtra("postTitle");
        postDetail = intent.getStringExtra("postDetail");
        postTime = intent.getStringExtra("postTime");
        postUser = intent.getStringExtra("postUser");
        postLikeNum = intent.getIntExtra("postLikeNum",0);
        postReplyNum = intent.getIntExtra("postReplyNum",0);

        //使用bundle接收
        Bundle bundle = intent.getExtras();
        BitmapBinder bitmapBinder = (BitmapBinder) bundle.getBinder("postImg");
        BitmapBinder userBitmapBinder = (BitmapBinder) bundle.getBinder("postUserImg");
        postImgBitmap = bitmapBinder.getBitmap();
        postUserImgBitmap = userBitmapBinder.getBitmap();

        //设定控件值
        titleView.setText(postTitle);
        detailView.setText(postDetail);
        timeView.setText(postTime);
        userView.setText(postUser);
        likeNumView.setText(String.valueOf(postLikeNum));
        replyNumView.setText(String.valueOf(postReplyNum));
        imageView.setImageBitmap(postImgBitmap);
        userImgView.setImageBitmap(postUserImgBitmap);

        //sharedPreference,获取用户名
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        username = sp.getString("user_name","");
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

    }

    //查询该帖子所有评论__msg2
    private Runnable getReplyRun = new Runnable() {
        @Override
        public void run() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                String sql = "select * from reply where r_postid="+postId;
                Statement st = (Statement)cn.createStatement();
                ResultSet rs = st.executeQuery(sql);
                System.out.println("连接数据库成功");

                rs.last(); // 将光标移动到最后一行
                int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
                Log.i(TAG, "run: 评论数量rowcount:"+rowCount);
                rs.beforeFirst();//将光标移回首行

                //查询出数据，将其放在List<Reply>中，使用adapter将其显示在列表里
                while (rs.next()){
                    Reply reply = new Reply();
                    reply.setR_content(rs.getString("r_content"));
                    reply.setR_time(rs.getString("r_time"));
                    reply.setR_uid(rs.getInt("r_uid"));
                    replyList.add(reply);
                }
                //对list进行按时间最新排序
                Collections.sort(replyList, new Comparator<Reply>(){

                    @Override
                    public int compare(Reply o1, Reply o2) {
                        if(o1.getR_time() == null || o2.getR_time() == null){
                            return -1;
                        }
                        if(o1.getR_time().length() > o2.getR_time().length()){
                            return -1;
                        }
                        if(o1.getR_time().length() < o2.getR_time().length()){
                            return 1;
                        }
                        if(o1.getR_time().compareTo(o2.getR_time()) > 0){
                            return -1;
                        }
                        if(o1.getR_time().compareTo(o2.getR_time()) < 0){
                            return 1;
                        }
                        if(o1.getR_time().compareTo(o2.getR_time()) == 0){
                            return 0;
                        }
                        return 0;
                    }

                });

                //遍历replylist，从数据库中查找用户头像、用户名
                for (Reply r : replyList) {
                    String sql2 = "select * from user where u_id="+r.getR_uid();
                    ResultSet rs2 = st.executeQuery(sql2);
                    System.out.println("连接数据库成功2");
                    rs2.next();
                    r.setR_userimg(rs2.getString("u_img"));
                    r.setR_user(rs2.getString("u_name"));
                    rs2.close();
                }

                //发送消息
                Message msg = handler.obtainMessage(2, 1);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---查询结果");

                rs.close();
                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //发布评论————插入数据库reply、修改post表中的replyNum、更新replyList__msg1
    private Runnable insertRun = new Runnable() {
        @Override
        public void run() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                Statement st = (Statement) cn.createStatement();
                int insertCode;
                try {
                    String insertSql = "INSERT INTO reply (r_uid,r_content,r_time,r_postid) VALUES (" + userId + ",'" + replyText + "','" + replyTime + "','" + postId + "')";
                    int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                    Log.i(TAG, "run: 插入数据成功" + result + "行----" + username);
                    insertCode = 1;

                    try {
                        String updateSql = "UPDATE post set p_replyNum = p_replyNum+1 where p_id="+postId;
                        int result2 = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                        Log.i(TAG, "run: 更新数据成功" + result2 + "行----" + postUser);

                        //更新listview
                        Reply reply = new Reply();
                        reply.setR_user(username);
                        reply.setR_content(replyText);
                        reply.setR_time(replyTime);
                        String sql2 = "select * from user where u_name='"+username+"';";
                        ResultSet rs2 = st.executeQuery(sql2);
                        System.out.println("更新list时查userimg，连接数据库成功2");
                        rs2.next();
                        String imgStr = rs2.getString("u_img");
                        reply.setR_userimg(imgStr);
                        rs2.close();
                        replyList.add(0, reply);

                    }catch (SQLException e){
                        Log.i(TAG, "run:SQL fail!!!__" + e);
                        e.printStackTrace();
                    }

                } catch (SQLException e) {
                    insertCode = 2;
                    Log.i(TAG, "run:SQL fail!!!__" + e);
                    e.printStackTrace();
                }

                //发送消息
                Message msg = handler.obtainMessage(1, insertCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---插入结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //发布评论
    public void giveReply(View view) {
        //出现弹窗填写评论
        final EditText inputServer = new EditText(PostDetailActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(PostDetailActivity.this);
        builder.setTitle("评论").setIcon(R.drawable.msg).setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("发布", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                replyText = inputServer.getText().toString();
                Log.i(TAG, "onClick: "+replyText);
                if(replyText.equals("")){
                    Toast.makeText(getApplicationContext(), "请填写评论", Toast.LENGTH_SHORT).show();
                }else{
                    //获取当前时间
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date date = new Date(System.currentTimeMillis());
                    Log.i(TAG, "获取当前时间:"+date);
                    replyTime = formatter.format(date);

                    //开启线程，提交评论，修改数据库post和reply
                    Thread thread = new Thread(insertRun);
                    thread.start();
                }

            }
        });
        builder.show();

    }

    //点赞————查询该帖子用户是否点赞、点赞数量__msg3
    private Runnable getLikeRun = new Runnable() {
        @Override
        public void run() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                String sql = "select * from likepost where l_postid="+postId;
                Statement st = (Statement)cn.createStatement();
                ResultSet rs = st.executeQuery(sql);
                System.out.println("查询点赞——连接数据库成功");

                rs.last(); // 将光标移动到最后一行
                int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
                Log.i(TAG, "run: 点赞数量rowcount:"+rowCount);
                rs.beforeFirst();//将光标移回首行

                //查询出数据，看该用户是否点赞
                while (rs.next()){
                    if(userId == rs.getInt("l_uid")){
                        //说明用户点过赞
                        likeStatus = true;
                    }
                }

                //发送消息
                Message msg = handler.obtainMessage(3, rowCount);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---查询结果");

                rs.close();
                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //点赞————点击“点赞”图标，更新post表中likenum
    private Runnable updatelikeRun = new Runnable() {
        @Override
        public void run() {
            int likeCode = 0;   //0取消还是1点赞
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                Statement st = (Statement) cn.createStatement();

                if(likeStatus){
                    //说明此时已经点赞，再次点击是“取消点赞”__删除数据
                    try {
                        String deleteSql = "DELETE FROM likepost WHERE l_uid = " + userId + " and l_postid = " + postId;
                        int result = st.executeUpdate(deleteSql);// 返回值代表收到影响的行数
                        Log.i(TAG, "run: 删除数据成功" + result + "行----" + username);
                        likeCode = 0;
                        likeStatus = false;

                        String updateSql = "UPDATE post set p_likeNum = p_likeNum-1 where p_id="+postId;
                        int result2 = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                        Log.i(TAG, "run: 更新数据成功" + result2 + "行----" + postUser);

                    } catch (SQLException e) {
                        Log.i(TAG, "run:SQL fail!!!__" + e);
                        e.printStackTrace();
                    }
                }else{
                    //点赞
                    try {
                        String insertSql = "INSERT INTO likepost (l_uid,l_postid) VALUES (" + userId + "," + postId + ")";
                        int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                        Log.i(TAG, "run: 插入数据成功" + result + "行----" + username);
                        likeCode = 1;
                        likeStatus = true;

                        String updateSql = "UPDATE post set p_likeNum = p_likeNum+1 where p_id="+postId;
                        int result2 = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                        Log.i(TAG, "run: 更新数据成功" + result2 + "行----" + postUser);

                    } catch (SQLException e) {
                        Log.i(TAG, "run:SQL fail!!!__" + e);
                        e.printStackTrace();
                    }
                }

                //发送消息
                Message msg = handler.obtainMessage(4, likeCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---更新点赞数据结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //点赞
    public void giveLike(View view) {
        //开启线程，更改点赞信息，修改数据库post和reply
        Thread thread = new Thread(updatelikeRun);
        thread.start();
    }

}